const Genre = require('../models/genre');
const Book = require('../models/book');
const async = require('async');

const {body,validationResult}  = require('express-validator/check');
const {sanitizeBody} = require('express-validator/filter');

exports.genre_list = (req,res,next)=>{
    Genre.find().sort([['name','ascending']]).exec(function (err, list_genre) {
        if(err){
            next(err)
        }else{
            res.render('genre_list',{title:'Genre列表',genre_list:list_genre})
        }
    });
};

exports.genre_detail = (req,res,next)=>{
    async.parallel({
        genre:function (cb) {
            Genre.findById(req.params.id).exec(cb);
        },
        genre_books:function (cb) {
            Book.find({'genre':req.params.id}).exec(cb)
        }
    },function (err, results) {
        if(err){
            next(err);
        }else if(results.genre==null){
            err = new Error('没有对应的分类');
            err.statusCode = 404;
            next(err);
        }else{
            res.render('genre_detail',{title:'分类的详情',genre:results.genre,genre_books:results.genre_books})
        }
    })
};

exports.genre_create_get = (req,res)=>{
    res.render('genre_form',{title:'创建分类'})
};
exports.genre_create_post = [
    body('name','分类名是必填项').isLength({min:1}).trim(),
    sanitizeBody('name').escape(),
    (req,res,next)=>{
        const errors = validationResult(req);
        let genre = new Genre({
            name:req.body.name
        });
        if(!errors.isEmpty()){
            res.render('genre_form',{title:'创建分类',genre,errors:errors.array()})
        }else{
            //check if genre name already exists
            Genre.findOne({name:req.body.name}).exec(function (err, found_genre) {
                if(err){
                    next(err);
                }else{
                    if(found_genre){
                        //genre exists,redirect to its detail page
                        res.redirect(found_genre.url);
                    }else{
                        genre.save(function (err) {
                            if(err){
                                next(err)
                            }else{
                                res.redirect(genre.url);
                            }
                        })
                    }
                }
            })
        }
    }
];

exports.genre_update_get = (req,res,next)=>{
    Genre.findById(req.params.id,function (err, genre) {
        if(err) return next(err);
        res.render('genre_form',{title:'编辑分类',genre});
    })
};
exports.genre_update_post =[
    body('name','name is required').isLength({min:2}).trim(),
    sanitizeBody('name').escape(),
    (req,res,next)=>{
        const errors = validationResult(req);
        const genre = new Genre({
            ...req.body,
            _id:req.params.id
        });
        if(!errors.isEmpty()){
            res.render('genre_form',{title:'请重新编辑分类',genre,errors:errors.array()})
        }else{
            Genre.findByIdAndUpdate(req.params.id,genre,{},function (err, theGenre) {
                if(err) return next(err);
                res.redirect(theGenre.url);
            })
        }
    }
];

exports.genre_delete_get = (req,res,next)=>{
    async.parallel({
        genre:function (cb) {
            Genre.findById(req.params.id).exec(cb);
        },
        genre_books:function (cb) {
            Book.find({genre:req.params.id}).exec(cb);
        }
    },function (err, results) {
        if(err) return next(err);
        res.render('genre_delete',{title:'删除分类',genre:results.genre,genre_books:results.genre_books})
    })
};
exports.genre_delete_post = (req,res,next)=>{
    async.parallel({
        genre:function (cb) {
            Genre.findById(req.params.id).exec(cb);
        },
        genre_books:function (cb) {
            Book.find({genre:req.params.id}).exec(cb);
        }
    },function (err, results) {
        if(err) return next(err);
        if(results.genre_books&&results.genre_books.length>0){
            res.render('genre_delete',{title:'删除分类',genre:results.genre,genre_books:results.genre_books})
        }else{
            Genre.findByIdAndRemove(req.params.id,function (err) {
                if(err) return next(err);
                res.redirect('/catalog/genres');
            })
        }
    })
};
